package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDTo;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory> implements CourseCategoryService {
    @Autowired
    private CourseCategoryMapper courseCategoryMapper ;

    @Override
    public List<CourseCategoryTreeDTo> queryTreeNodes() {

        List<CourseCategory> categoryList = courseCategoryMapper.selectList(null);

        List<CourseCategoryTreeDTo> categoryDTos = new ArrayList<>();
        List<CourseCategoryTreeDTo> categoryTreeDToList = new ArrayList<>();

        for (CourseCategory courseCategory : categoryList) {
            CourseCategoryTreeDTo categoryTreeDTo = new CourseCategoryTreeDTo();
            BeanUtils.copyProperties(courseCategory, categoryTreeDTo);
            categoryDTos.add(categoryTreeDTo);
        }
        HashMap<String,CourseCategoryTreeDTo> nodeMap = new HashMap<>() ;

        categoryDTos.stream().forEach(item->{
            nodeMap.put(item.getId(),item);
            if(item.getParentid().equals("1")){
                categoryTreeDToList.add(item);
            }

            String parentid = item.getParentid() ;

            CourseCategoryTreeDTo parentNode = nodeMap.get(parentid);

            if(parentNode!=null){
                List childrenTreeNodes = parentNode.getChildrenTreeNodes();
                if(childrenTreeNodes == null){
                    parentNode.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDTo>());
                }
                parentNode.getChildrenTreeNodes().add(item) ;
            }
        });

        return categoryTreeDToList ;
    }
}
